package cc.customer.cRound.service.Impl;

import cc.customer.cRound.dao.CRoundConfigMapper;
import cc.customer.cRound.dao.CRoundGradeMapper;
import cc.customer.cRound.dao.CRoundLevelMapper;
import cc.customer.cRound.domain.CRoundConfig;
import cc.customer.cRound.domain.CRoundGrade;
import cc.customer.cRound.domain.CRoundLevel;
import cc.customer.cRound.service.CRoundLevelService;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.Utils;
import cc.customer.cusDynamic.services.impl.CusDynamicImpl;
import cc.customer.system.dao.GradeMapper;
import cc.customer.system.dao.UserMapper;
import cc.customer.system.domain.Grade;
import cc.customer.system.domain.MyUser;
import com.mysql.jdbc.log.LogFactory;
import org.apache.commons.lang3.StringUtils;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class CRoundLevelServiceImpl extends BaseService<CRoundLevel> implements CRoundLevelService{

    private static final Logger logger = LoggerFactory.getLogger(CRoundLevelServiceImpl.class);

    @Autowired
    private CRoundLevelMapper levelMapper;
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CRoundConfigMapper configMapper;


    @Override
    public ResponseBo addNewLevel(CRoundLevel level){
        try {
            String[] users = level.getlIntPerson().split(",");
            List<String> uselist = Arrays.asList(users);

            Example example = new Example(MyUser.class);
            example.createCriteria().andIn("dingUserid",uselist);
            List<MyUser> userList = userMapper.selectByExample(example);

            List<Grade> gradeList = gradeMapper.selectAll();

            List<CRoundLevel> addList = new ArrayList<>();
            List<CRoundLevel> updateList = new ArrayList<>();
            List<CRoundLevel> deleteList = new ArrayList<>();

            for(Grade grade:gradeList){
                Example example1 = new Example(CRoundLevel.class);
                StringBuffer bs = new StringBuffer();
                for(MyUser user:userList){
                    if(user.getGrade().equals(grade.getgId()+"")){
                        bs.append(user.getDingUserid()).append(",");
                    }
                }
                String bss = bs.toString();
                String ids = "";
                if(bss.contains(",")){
                    ids = bss.substring(0,bss.lastIndexOf(","));
                }
                example1.createCriteria().andEqualTo("lGradeid",grade.getgId()).andEqualTo("lUuid",level.getlUuid())
                        .andEqualTo("lType",level.getlType()).andEqualTo("lDeptid",level.getlDeptid());
                List<CRoundLevel> levelList = levelMapper.selectByExample(example1);

                if(levelList.size()>0){
                     CRoundLevel lev = levelList.get(0);
                    if(!StringUtils.isEmpty(ids)){
                        //更新
                        if(lev.getlGradeid().equals(grade.getgId()+"")){
                            if(!StringUtils.isEmpty(ids)){
                                lev.setlIntPerson(ids);
                                updateList.add(lev);
                            }
                        }else{
                            CRoundLevel roundLevel = new CRoundLevel();
                            roundLevel.setlUuid(level.getlUuid());
                            roundLevel.setlDeptid(level.getlDeptid());
                            roundLevel.setlIntPerson(ids);
                            roundLevel.setlGradeid(grade.getgId()+"");
                            roundLevel.setlType(level.getlType());
                            addList.add(roundLevel);
                        }
                    }else{
                        deleteList.add(lev);
                    }
                }else{
                    //添加
                    if(!StringUtils.isEmpty(ids)){
                        CRoundLevel roundLevel = new CRoundLevel();
                        roundLevel.setlUuid(level.getlUuid());
                        roundLevel.setlDeptid(level.getlDeptid());
                        roundLevel.setlIntPerson(ids);
                        roundLevel.setlGradeid(grade.getgId()+"");
                        roundLevel.setlType(level.getlType());
                        addList.add(roundLevel);
                    }
                }
            }

            logger.info("更新的数目:"+updateList.size());
            if(!updateList.isEmpty()){
                /**判断是不是减少了人员  如果是减少，则立马执行**/
                updateList.stream().forEach(list->{
                    String init = list.getlIntPerson();
                    List<String> initlist = new ArrayList<>(Arrays.asList(init.split(",")));
                    String persion = list.getlPerson();
                    if (!StringUtils.isEmpty(persion)){
                        List<String> persionlist = new ArrayList<>(Arrays.asList(persion.split(",")));
                        List<String> del = new ArrayList<>();
                        for (String p:persionlist){
                            boolean ble = true;
                            for (String c:initlist){
                                if (c.equals(p)){
                                    ble = false;
                                    break;
                                }
                            }
                            if (ble){
                                del.add(p);
                            }
                        }
                        persionlist.removeAll(del);
                        list.setlPerson(StringUtils.join(persionlist,","));
                    }

                });
                levelMapper.batchUpdateLever(updateList);
            }

            logger.info("新增的数目:"+addList.size());
            if(!addList.isEmpty()){
                boolean ble = true;
                Example exa = new Example(CRoundConfig.class);
                exa.createCriteria().andEqualTo("cPid",level.getlUuid());
                List<CRoundConfig> levelList = configMapper.selectByExample(exa);
                for (CRoundConfig levelde :levelList) {
                    logger.info(!StringUtils.isEmpty(levelde.getcRdrecorder())+"");
                    if (!StringUtils.isEmpty(levelde.getcRdrecorder())){
                        ble = false;
                        break;
                    }
                }
                for(CRoundLevel list:addList){
                    String p = list.getlIntPerson();
                    if (ble){
                        list.setlPerson(p);
                    }
                }
                levelMapper.insertList(addList);
            }

            logger.info("删除的数目:"+addList.size());
            if(!deleteList.isEmpty()){
                for(CRoundLevel ll:deleteList){
                    levelMapper.delete(ll);
                }
            }
            return ResponseBo.ok("添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBo.error("添加失败");
        }
    }

    @Override
    public ResponseBo getUserInfoById(CRoundLevel level){
        try {
            Example e = new Example(CRoundLevel.class);
            e.createCriteria().andEqualTo("lUuid",level.getlUuid()).andEqualTo("lDeptid",level.getlDeptid()).andEqualTo("lType",level.getlType());
            List<CRoundLevel> list = this.selectByExample(e);
            return ResponseBo.ok("",list);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBo.error();
        }
    }
}
